package com.teo.opengl.tuts;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import java.util.Random;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLU;

public class OpenGLRenderer implements Renderer {

	private Square square;
	
	public OpenGLRenderer()
	{
		square = new Square();
	}
	
	float tx=0.0f, ty=0.0f, tz=-4.0f;
	
	Random r = new Random();
	
	public void onDrawFrame(GL10 gl) {
		// Clears the screen and depth buffer
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		
		gl.glLoadIdentity();
		
		/*
		tx += r.nextFloat() > 0.5 ? r.nextFloat() : (-1) * r.nextFloat();
		ty += r.nextFloat() > 0.5 ? r.nextFloat() : (-1) * r.nextFloat();
		tz += r.nextFloat() > 0.5 ? r.nextFloat() : (-1) * r.nextFloat();
		
		
		System.out.println("translation: " + tx + " " + ty + " " + tz);
		*/
		// Translates 4 units into the screen
		gl.glTranslatef(tx, ty, tz);
		
		square.draw(gl);
		
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// sets the curretn viewport to the new size
		gl.glViewport(0, 0, width, height);
		
		// select the projection matrix
		gl.glMatrixMode(GL10.GL_PROJECTION);
		
		// reset the projection matrix
		gl.glLoadIdentity();
		
		// calculate the aspect ratio of the window
		GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f);
		
		//select the modelview matrix
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		
		//reset the modelview matrix
		gl.glLoadIdentity();
		
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {

		// set the bg color to black (rgba)
		gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
		// Enable Smooth Shading, default not really needed	
		gl.glShadeModel(GL10.GL_SMOOTH);
		// Depth buffer setup
		gl.glClearDepthf(1.0f);
		
		// Enables depth testing
		gl.glEnable(GL10.GL_DEPTH_TEST);
		// The type of depth testing to do
		gl.glDepthFunc(GL10.GL_LEQUAL);
		// Really nice perspective calculations
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
				GL10.GL_NICEST);
		
		System.out.println("creating the square");
	}
	

}
